<template>
  <div class="component-upload-image">
    
    <!--图片展示-->
    <div class="img_item" v-for="(item,indx) in urlList">
      <el-image style="width: 90px;height: 90px;margin-right:10px;margin-bottom: 10px;border-radius:10px;" fit="cover"
                :preview-src-list="urlList" :src="item"/>
      <i class="el-icon-error icon" @click="handleDel(indx)"/>
    </div>
    
    <!--图片上传-->
    <el-upload multiple :action="imgUrl + '/common/upload'" list-type="picture-card" :on-success="handleUploadSuccess"
               :before-upload="handleBeforeUpload" :limit="limit" :on-error="handleUploadError"
               :on-exceed="handleExceed" ref="imageUploadRef" :on-remove="handleDelete" :show-file-list="false"
               :headers="headers" :file-list="fileList" :class="{hide: this.fileList.length >= this.limit}">
      <i class="el-icon-plus"></i>
    </el-upload>
  </div>
</template>

<script>
    import {getToken} from "@/utils/auth";
    import env from "@/utils/config.js";

    export default {
        props: {
            value: [String, Object, Array],
            // 图片数量限制
            limit: {
                type: Number,
                default: 10,
            },
            // 大小限制(MB)
            fileSize: {
                type: Number,
                default: 5,
            },
            // 文件类型, 例如['png', 'jpg', 'jpeg']
            fileType: {
                type: Array,
                default: () => ["png", "jpg", "jpeg"],
            },
            // 是否显示提示
            isShowTip: {
                type: Boolean,
                default: true
            },
        },

        data() {
            return {
                number: 0,
                uploadList: [],
                dialogImageUrl: "",
                dialogVisible: false,
                hideUpload: false,
                baseUrl: process.env.VUE_APP_BASE_API,
                uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
                headers: {
                    Authorization: "Bearer " + getToken(),
                },
                fileList: [],
                imgUrl: '',
                urlList: []
            };
        },
        watch: {
            value: {
                handler(val) {
                    if (val) {
                        // 首先将值转为数组
                        const list = Array.isArray(val) ? val : this.value.split(',');
                        this.urlList = list;
                    } else {
                        this.urlList = [];
                        return [];
                    }
                },
                deep: true,
                immediate: true
            }
        },
        computed: {
            // 是否显示提示
            showTip() {
                return this.isShowTip && (this.fileType || this.fileSize);
            },
        },
        methods: {
            // 上传前loading加载
            handleBeforeUpload(file) {
                this.$modal.loading("正在上传图片，请稍候...");
            },
            // 文件个数超出
            handleExceed() {
                this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
            },

            // 删除
            handleDel(index) {
                this.urlList.splice(index, 1);
            },

            // 上传成功回调
            handleUploadSuccess(res, file, fileList) {
                this.$modal.closeLoading();
                if (fileList.every(i => i.status == 'success')) {
                    fileList.forEach(item => {
                        this.urlList.push(item.response.url);
                    });
                    this.$emit('cbImg', this.urlList);
                    this.$refs.imageUploadRef && this.$refs.imageUploadRef.clearFiles()
                }
            },
            // 删除图片
            handleDelete(file) {
                const findex = this.fileList.map(f => f.name).indexOf(file.name);
                if (findex > -1) {
                    this.fileList.splice(findex, 1);
                    this.$emit("input", this.listToString(this.fileList));
                }
            },
            // 上传失败
            handleUploadError() {
                this.$modal.msgError("上传图片失败，请重试");
                this.$modal.closeLoading();
            },

            // 对象转成指定字符串分隔
            listToString(list, separator) {
                let strs = "";
                separator = separator || ",";
                for (let i in list) {
                    if (list[i].url) {
                        strs += list[i].url.replace(this.baseUrl, "") + separator;
                    }
                }
                return strs != '' ? strs.substr(0, strs.length - 1) : '';
            }
        },
        created() {
            this.imgUrl = env;
        },
    };
</script>
<style scoped lang="scss">
  // .el-upload--picture-card 控制加号部分
  ::v-deep.hide .el-upload--picture-card {
  }
  
  // 去掉动画效果
  ::v-deep .el-list-enter-active,
  ::v-deep .el-list-leave-active {
    transition: all 0s;
  }
  
  ::v-deep .el-list-enter, .el-list-leave-active {
    opacity: 0;
    transform: translateY(0);
  }
  
  ::v-deep .el-upload--picture-card {
    width: 90px !important;
    height: 90px !important;
    line-height: 90px !important;
  }
  
  .component-upload-image {
    display: flex;
    flex-wrap: wrap;
    
    .img_item {
      position: relative;
      
      .icon {
        position: absolute;
        top: -8px;
        right: 2px;
        z-index: 100;
        font-size: 20px;
        cursor: pointer;
      }
    }
  }
</style>

